/**
 * 对企业微信发送给企业后台的消息加解密示例代码.
 * 
 * @copyright Copyright (c) 1998-2014 Tencent Inc.
 */

// ------------------------------------------------------------------------

/**
 * 针对org.apache.commons.codec.binary.Base64，
 * 需要导入架包commons-codec-1.9（或commons-codec-1.8等其他版本）
 * 官方下载地址：http://commons.apache.org/proper/commons-codec/download_codec.cgi
 */
package com.dzl.util.wx.mp.aes;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dzl.util.EmptyUtils;
import com.dzl.util.HttpUtil;
import com.dzl.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Node;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

/**
 * 企业微信工具类
 * @author liuguanjun
 * @date 2021-12-10 10:48
 */
@Slf4j
public class WXMsgUtils {

	public static String sToken = "AFt0tTJ4NcBAAuYAjM1znHoAdfh";
	//企业ID
	public static String sCorpID = "ww8758212cee41fe02";
	public static String sEncodingAESKey = "2xHwfVWxuQMiw6jGzm48SHYSnv6alCMfpNH9ANrJCGN";

	//应用的凭证密钥
	public static String SECRET = "-dHHILcya-MbzkGNyvdpS8mGKf7s4yF8fOQ-r4TMQ9I";

	//接收消息Url
	public static String SYNC_MSG_URL = "https://qyapi.weixin.qq.com/cgi-bin/kf/sync_msg?access_token=ACCESS_TOKEN";
	//发送消息Url
	public static String SEND_MSG_URL = "https://qyapi.weixin.qq.com/cgi-bin/kf/sync_msg?access_token=ACCESS_TOKEN";
	//获取会话状态Url
	public static String GET_SERVICE_STATE_URL = "https://qyapi.weixin.qq.com/cgi-bin/kf/service_state/get?access_token=ACCESS_TOKEN";
	//变更会话状态url
	public static String TRANS_SERVICE_STATE_URL = "https://qyapi.weixin.qq.com/cgi-bin/kf/service_state/trans?access_token=ACCESS_TOKEN";
	//删除客服帐号Url
	public static String ACCOUNT_DELETE_URL = "https://qyapi.weixin.qq.com/cgi-bin/kf/account/del?access_token=ACCESS_TOKEN" ;
	//添加客服帐号url
	public static String ACCOUNT_ADD_URL = "https://qyapi.weixin.qq.com/cgi-bin/kf/account/add?access_token=ACCESS_TOKEN";
	//修改客服帐号url
	public static String ACCOUNT_UPDATE_URL = "https://qyapi.weixin.qq.com/cgi-bin/kf/account/update?access_token=ACCESS_TOKEN";
	//获取客服帐号列表url
	public static String ACCOUNT_LIST_URL = "https://qyapi.weixin.qq.com/cgi-bin/kf/account/list?access_token=ACCESS_TOKEN";

	//删除接待人员Url
	public static String SERVICER_DELETE_URL = "https://qyapi.weixin.qq.com/cgi-bin/kf/servicer/del?access_token=ACCESS_TOKEN" ;
	//添加接待人员url
	public static String SERVICER_ADD_URL = "https://qyapi.weixin.qq.com/cgi-bin/kf/servicer/add?access_token=ACCESS_TOKEN";
	//获取接待人员列表url
	public static String SERVICER_LIST_URL = "https://qyapi.weixin.qq.com/cgi-bin/kf/servicer/list?access_token=ACCESS_TOKEN&open_kfid=OPEN_KFID";
	//发送欢迎语等事件响应消息
	public static String SEND_MSG_ON_EVENT_URL = "https://qyapi.weixin.qq.com/cgi-bin/kf/send_msg_on_event?access_token=ACCESS_TOKEN";

	public static void main(String[] args) throws Exception {

		/*WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID);
		String sVerifyMsgSig = URLDecoder.decode("67f0d5dc03f296934095011a7cde7d250d0600c4","UTF-8");
		String sVerifyTimeStamp = URLDecoder.decode("1639376021","UTF-8");
		String sVerifyNonce = URLDecoder.decode("3oay64xkfs6","UTF-8");
		String echostr = "q9v1mdbDK2ydGKzU9DRqhHNtBxGjzo01zKsogtPG5XW4Q3vZL8gAA+c6BYfC5qTAxUHVtTLxsPExghfsZ8mWTg==";
		String sEchoStr = wxcpt.VerifyURL(sVerifyMsgSig, sVerifyTimeStamp,sVerifyNonce, echostr);
		System.out.println(sEchoStr);*/

		/*String xml = "<xml><ToUserName><![CDATA[ww8758212cee41fe02]]></ToUserName><Encrypt><![CDATA[N990VnxZ+5znzWJvtJQSP8fC+ROlse7P5Gj0QHcFl5yh9Fc2TTrHtPn5DDi/vpAy6EAEHmOW57OuWrLmCJNoVtf+w/3pXHBTGSUSe6Dq9xF/2XhNO+t/aY1U4mcotrgZ/+ycvaMytxaeUCX2ag0iTneLnraJzMkhZ0fP6XzROjXIPSXuMH5xH3A/Cf+DXLrxlaffrtmMGOhC6zoyuADHGlLZaJ7AHCUjHzliQVvj92L4da90TZJfIJcK0x3QCRHj5Io0EPPhyUc5QhI+uh0y8V56LjJiHgiap1437e2X43STn/BWvky3WVbzBGaeeyEon8/wiXgxLBO0P/YqWL7IetDR70zIJNySBL0NXBVDgA5Zv1hQ4lmw8n1h12H2NHlNUj4zFthGf247kuYfHC74qX4SGiRTbmpBe4T5jG7NcyY=]]></Encrypt><AgentID><![CDATA[]]></AgentID></xml>";
		String result = getTokenFromXml(xml);
		System.out.println(result.toString());*/

		//获取客服帐号列表
		//getAccountList();

		//修改微信客服
		updateAccount("wkvAoNDwAAGhpk0GUr4muWuj26ruyR0w","福力兔客服","");

		//删除微信客服
		//deleteAccount("wkvAoNDwAArcdB2pkf40dYZocUETA31A");

		//获取客服帐号列表
		//getServicerList("wkvAoNDwAAGhpk0GUr4muWuj26ruyR0w");

		//添加客服帐号
		/*List<String> userids = new ArrayList<>();
		userids.add("YiXi");
		addServicer("wkvAoNDwAAGhpk0GUr4muWuj26ruyR0w",userids);*/

		//删除客服帐号
		/*List<String> userids = new ArrayList<>();
		userids.add("LiuGuanJun");
		userids.add("long");
		userids.add("XiaoXiaoXiaoYuDi");
		deleteServicer("wkvAoNDwAAGhpk0GUr4muWuj26ruyR0w",userids);*/
	}

	//获取客服帐号列表
	public static String getAccountList(){
		String accessToken = WXMsgUtils.getAccessToken();
		String getAccountListUrl = WXMsgUtils.ACCOUNT_LIST_URL.replace("ACCESS_TOKEN", accessToken);
		String getAccountListResult = HttpUtil.sendGet(getAccountListUrl,"utf-8");
		if(EmptyUtils.isNotEmpty(getAccountListResult)) {
			JSONObject getAccountListResultJsonObject = JSONObject.parseObject(getAccountListResult);
			if (getAccountListResultJsonObject.getInteger("errcode") == 0) {
				JSONArray jsonArray = getAccountListResultJsonObject.getJSONArray("account_list");
				if(EmptyUtils.isNotEmpty(jsonArray) && jsonArray.size()>0){
					for (Object obj: jsonArray){
						JSONObject jsonObject = (JSONObject)obj;
						log.info("WXMsgUtils=================================>获取客服帐号列表: open_kfid:"+jsonObject.get("open_kfid")
								+",name:"+jsonObject.get("name")+",avatar:"+jsonObject.get("avatar"));
					}
				}
			}
		}
		return getAccountListResult;
	}

	//修改微信客服
	public static String updateAccount(String open_kfid, String name,String media_id) throws IOException {
		String accessToken = WXMsgUtils.getAccessToken();
		String updateAccountUrl = WXMsgUtils.ACCOUNT_UPDATE_URL.replace("ACCESS_TOKEN", accessToken);
		JSONObject updateAccountParam = new JSONObject();
		updateAccountParam.put("open_kfid", open_kfid);//wkvAoNDwAArcdB2pkf40dYZocUETA31A
		updateAccountParam.put("name", name);
		//updateAccountParam.put("media_id", media_id);
		String updateAccountResult = HttpUtil.sendPostUrl(updateAccountUrl,updateAccountParam,"utf-8");
		log.info("WXMsgUtils=================================>修改微信客服: updateAccountResult:"+updateAccountResult);
		return updateAccountResult;
	}

	//删除微信客服
	public static String deleteAccount(String open_kfid) throws IOException {
		String accessToken = WXMsgUtils.getAccessToken();
		String deleteAccountUrl = WXMsgUtils.ACCOUNT_DELETE_URL.replace("ACCESS_TOKEN", accessToken);
		JSONObject deleteAccountParam = new JSONObject();
		deleteAccountParam.put("open_kfid", open_kfid);//wkvAoNDwAArcdB2pkf40dYZocUETA31A
		String deleteAccountResult = HttpUtil.sendPostUrl(deleteAccountUrl,deleteAccountParam,"utf-8");
		log.info("WXMsgUtils=================================>删除微信客服: deleteAccountResult:"+deleteAccountResult);
		return deleteAccountResult;
	}

	//获取接待人员列表
	public static String getServicerList(String open_kfid){
		String accessToken = WXMsgUtils.getAccessToken();
		String getServicerListUrl = WXMsgUtils.SERVICER_LIST_URL.replace("ACCESS_TOKEN", accessToken).replace("OPEN_KFID",open_kfid);
		String getServicerListResult = HttpUtil.sendGet(getServicerListUrl,"utf-8");
		if(EmptyUtils.isNotEmpty(getServicerListResult)) {
			JSONObject getServicerListResultJsonObject = JSONObject.parseObject(getServicerListResult);
			if (getServicerListResultJsonObject.getInteger("errcode") == 0) {
				JSONArray jsonArray = getServicerListResultJsonObject.getJSONArray("servicer_list");
				if(EmptyUtils.isNotEmpty(jsonArray) && jsonArray.size()>0){
					for (Object obj: jsonArray){
						JSONObject jsonObject = (JSONObject)obj;
						log.info("WXMsgUtils=================================>获取接待人员列表: userid:"+jsonObject.get("userid")
								+",status:"+jsonObject.get("status"));
					}
				}
			}
		}
		return getServicerListResult;
	}

	//添加接待人员
	public static String addServicer(String open_kfid, List<String> userid_list) throws IOException {
		String accessToken = WXMsgUtils.getAccessToken();
		String addServicerUrl = WXMsgUtils.SERVICER_ADD_URL.replace("ACCESS_TOKEN", accessToken);
		JSONObject addServicerParam = new JSONObject();
		addServicerParam.put("open_kfid", open_kfid);//wkvAoNDwAArcdB2pkf40dYZocUETA31A
		JSONArray userids = JSONArray.parseArray(JSON.toJSONString(userid_list));
		addServicerParam.put("userid_list", userids);
		String addServicerResult = HttpUtil.sendPostUrl(addServicerUrl,addServicerParam,"utf-8");
		log.info("WXMsgUtils=================================>添加微信客服: addServicerResult:"+addServicerResult);
		return addServicerResult;
	}

	//删除接待人员
	public static String deleteServicer(String open_kfid, List<String> userid_list) throws IOException {
		String accessToken = WXMsgUtils.getAccessToken();
		String deleteServicerUrl = WXMsgUtils.SERVICER_DELETE_URL.replace("ACCESS_TOKEN", accessToken);
		JSONObject deleteServicerParam = new JSONObject();
		deleteServicerParam.put("open_kfid", open_kfid);//wkvAoNDwAArcdB2pkf40dYZocUETA31A
		JSONArray userids = JSONArray.parseArray(JSON.toJSONString(userid_list));
		deleteServicerParam.put("userid_list", userids);
		String deleteServicerResult = HttpUtil.sendPostUrl(deleteServicerUrl,deleteServicerParam,"utf-8");
		log.info("WXMsgUtils=================================>删除接待人员: deleteServicerResult:"+deleteServicerResult);
		return deleteServicerResult;
	}

	public static void sendMsg(JSONObject msgJsonObject) throws IOException {
		String accessToken = WXMsgUtils.getAccessToken();
		//发送消息
		String sendMsgUrl = WXMsgUtils.SEND_MSG_URL.replace("ACCESS_TOKEN", accessToken);
		String msgtype = msgJsonObject.getString("msgtype");
		if(msgtype.equals("text")){//文本消息
			msgJsonObject.put("touser",msgJsonObject.get("external_userid"));
			String sendMsgResult = HttpUtil.sendPostUrl(sendMsgUrl,msgJsonObject,"utf-8");
			log.info("ReceiveEneterpriseWechatMsg=================================>发送消息：touser:"+msgJsonObject.get("external_userid")+",open_kfid:"+msgJsonObject.get("open_kfid")
					+",msgid:"+msgJsonObject.get("msgid")+",msgtype:"+msgJsonObject.get("msgtype")+",content:"+msgJsonObject.get("text")+",result:"+sendMsgResult);
			if(EmptyUtils.isNotEmpty(sendMsgResult)){
				JSONObject sendMsgResultJsonObject = JSONObject.parseObject(sendMsgResult);
				if(sendMsgResultJsonObject.getInteger("errcode") == 0){
					//获取会话状态
					String getServiceStateUrl = WXMsgUtils.GET_SERVICE_STATE_URL.replace("ACCESS_TOKEN", accessToken);
					JSONObject getServiceStateParam = new JSONObject();
					getServiceStateParam.put("open_kfid",msgJsonObject.get("open_kfid"));
					getServiceStateParam.put("external_userid",msgJsonObject.get("external_userid"));
					String getServiceStateResult = HttpUtil.sendPostUrl(getServiceStateUrl,getServiceStateParam,"utf-8");
					log.info("ReceiveEneterpriseWechatMsg=================================>获取会话状态：getServiceStateResult:"+getServiceStateResult+",open_kfid:"+getServiceStateParam.get("open_kfid")
							+",external_userid:"+getServiceStateParam.get("external_userid")+",service_state:"+getServiceStateParam.get("service_state")+",servicer_userid:"+getServiceStateParam.get("servicer_userid"));
					if(EmptyUtils.isNotEmpty(getServiceStateResult)) {
						JSONObject getServiceStateResultJsonObject = JSONObject.parseObject(getServiceStateResult);
						if (getServiceStateResultJsonObject.getInteger("errcode") == 0) {
							//变更会话状态
							String transServiceStateUrl = WXMsgUtils.TRANS_SERVICE_STATE_URL.replace("ACCESS_TOKEN", accessToken);
							JSONObject transServiceStateParam = new JSONObject();
							transServiceStateParam.put("open_kfid",msgJsonObject.get("open_kfid"));
							transServiceStateParam.put("external_userid",msgJsonObject.get("external_userid"));
							transServiceStateParam.put("service_state", 2);
							transServiceStateParam.put("servicer_userid",getServiceStateResultJsonObject.get("servicer_userid"));
							String transServiceStateResult = HttpUtil.sendPostUrl(transServiceStateUrl,transServiceStateParam,"utf-8");
							log.info("ReceiveEneterpriseWechatMsg=================================>变更会话状态：transServiceStateResult:"+transServiceStateResult+",open_kfid:"+transServiceStateParam.get("open_kfid")
									+",external_userid:"+transServiceStateParam.get("external_userid")+",service_state:"+transServiceStateParam.get("service_state")+",servicer_userid:"+transServiceStateParam.get("servicer_userid"));
						}
					}
				}
			}
		}else if(msgtype.equals("image")){//图片消息

		}else if(msgtype.equals("voice")){//语音消息

		}else if(msgtype.equals("video")){//视频消息

		}else if(msgtype.equals("file")){//文件消息

		}else if(msgtype.equals("location")){//位置消息

		}else if(msgtype.equals("link")){//链接消息

		}else if(msgtype.equals("business_card")){//名片消息

		}else if(msgtype.equals("miniprogram")){//小程序消息

		}else if(msgtype.equals("msgmenu")){//菜单消息

		}else if(msgtype.equals("event")){//事件消息

		}
	}

	public static String getTokenFromXml(String xmltext) throws DocumentException {
		Document document= DocumentHelper.parseText(xmltext);//xmlStr为上图格式的字符串

		Node ToUserName=document.selectSingleNode("//ToUserName");//获取节点对象,注意引号内的“//”必须加 ，否则报错
		Node Token=document.selectSingleNode("//Token");
		//根据节点对象获取相应信息
		String ToUserNameStr = ToUserName.getText();
		String TokenStr = Token.getText();
		System.out.println(TokenStr); //此时输出结果极为字符串：3333
		return TokenStr;
	}

	/**
	 * 获取access_token
	 * 获取access_token是调用企业微信API接口的第一步，相当于创建了一个登录凭证，其它的业务API接口，都需要依赖于access_token来鉴权调用者身份。
	 * 因此开发者，在使用业务接口前，要明确access_token的颁发来源，使用正确的access_token。
	 */
	public static String getAccessToken()  {
		//return "-DTv_h4QB_pE_ZcenFc4omBbD_To1sJkSaQnxWKsj7lz_hOyxkpz_fDJDzo3YBTvHc3X97NEDcKAcb9GHMdkO5z2FiHUIWZu5kJqKb4J599l3lnMAy3bUEqD8d6qo8tG37V7aiKnRpJ6e3RxaaEJsXO8BbnkH9LMubw0HUg9X6l36BQold2_u9O36clA0jab1oDygUN4lLbmtNau_3YRFg";
		if(RedisUtil.get("WX:ACCESS_TOKEN")!=null){
			String accessToken = (String) RedisUtil.get("WX:ACCESS_TOKEN");
			log.info("accessToken is "+accessToken);
			return accessToken;
		}
		String getAccessTokenUrl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="+sCorpID+"&corpsecret="+SECRET;
		String result = HttpUtil.sendGet(getAccessTokenUrl,"utf-8");
		if(EmptyUtils.isNotEmpty(result)){
			JSONObject resultJson = JSONObject.parseObject(result);
			if (resultJson.getInteger("errcode") == 0) {
				RedisUtil.set("WX:ACCESS_TOKEN", resultJson.getString("access_token"), 60 * 60 * 2);//缓存2小时
				log.info("token is "+resultJson.getString("access_token"));
				return resultJson.getString("access_token");
			}
		}
		return null;
	}

	/**
	 * 加密字符串读取
	 */
	public static String readAsChars(HttpServletRequest request)  {
		BufferedReader br = null;
		StringBuilder sb = new StringBuilder("");
		try {
			br = request.getReader();
			String str ;
			while ((str = br.readLine()) != null){
				sb.append(str);
			}
			br.close();
		}catch (Exception e){
			e.printStackTrace();
		}finally {
			if(null != br){
				try {
					br.close();
				}catch (IOException e){
					e.printStackTrace();
				}
			}
		}
		return sb.toString();
	}



}